from django.http import JsonResponse
from django.shortcuts import render,redirect,reverse
from adminApp.models import Information, InformationComment
from authApp.models import UserInfo
from clientApp.models import TyphoonBasicInfo,TyphoonLocationInfo,TyphoonGradeInfo
from django.db.models import Avg, Max, Count
from django.views.decorators.http import require_POST
import pandas as pd

# Create your views here.
def get_years():
    queryset = TyphoonBasicInfo.objects.exclude(Typhoon_OnsetTime__isnull=True).values('Typhoon_OnsetTime')
    # 将 queryset 转换为 pandas DataFrame
    df = pd.DataFrame(list(queryset))
    # 提取年份
    df['year'] = pd.to_datetime(df['Typhoon_OnsetTime']).dt.year
    # 获取不重复的年份
    unique_years = df['year'].dropna().unique()
    return unique_years
def index(request):
    print(request.session['user_email'])
    # 获取不重复的年份
    unique_years = get_years()
    return render(request, 'index.html',{
        'years': unique_years
    })
def selected_get_typhoon(request):
    selected_year = request.GET.get('year', None)
    if not selected_year:
        return JsonResponse({'status': False, 'error': '该内容不存在' })
    typhoons = TyphoonBasicInfo.objects.filter(Typhoon_OnsetTime__year=selected_year).values('Typhoon_Id', 'Typhoon_CName', 'Typhoon_EName','Typhoon_StopOrNot')
    typhoon_data = list(typhoons)
    print(typhoon_data)
    return JsonResponse({'status': True, 'data': typhoon_data})

def list_get_path(request):
    typhoon_id = request.POST.get('typhoon_id',None)
    if not typhoon_id:
        return JsonResponse({'status': False, 'error': '该内容不存在'})
    typhoons = TyphoonLocationInfo.objects.filter(Typhoon_Id=typhoon_id).values('Typhoon_PathId','Typhoon_Longitude','Typhoon_Latitude','Typhoon_CurrentTime')
    typhoon_grade_info = TyphoonGradeInfo.objects.filter(
        Typhoon_PathId__in=[point['Typhoon_PathId'] for point in typhoons]
    ).values('Typhoon_PathId', 'Typhoon_WindSpeed', 'Typhoon_Intensity', 'Typhoon_Level', 'Typhoon_Pressure')

    # 将查询结果根据 Typhoon_PathId 分组
    grade_info_dict = {}
    for info in typhoon_grade_info:
        path_id = info['Typhoon_PathId']
        if path_id not in grade_info_dict:
            grade_info_dict[path_id] = {
                'wind_speed': info['Typhoon_WindSpeed'],
                'intensity': info['Typhoon_Intensity'],
                'level': info['Typhoon_Level'],
                'pressure': info['Typhoon_Pressure']
            }
    # 格式化数据
    typhoon_paths = [
        {
            'id': point['Typhoon_PathId'],
            'lat': point['Typhoon_Latitude'],
            'lng': point['Typhoon_Longitude'],
            'time': point['Typhoon_CurrentTime'],
            'speed': grade_info_dict.get(point['Typhoon_PathId'], {}).get('wind_speed'),
            'intensity': grade_info_dict.get(point['Typhoon_PathId'], {}).get('intensity'),
            'level': grade_info_dict.get(point['Typhoon_PathId'], {}).get('level'),
            'pressure': grade_info_dict.get(point['Typhoon_PathId'], {}).get('pressure')
        }
        for point in typhoons
    ]
    typhoon_paths_sorted = sorted(typhoon_paths, key=lambda x: int(x['id'].split('_')[1]))
    print(typhoon_paths_sorted)
    return JsonResponse({'status': True, 'data': typhoon_paths_sorted})

def typhoon_info(request):
    # 获取不重复的年份
    unique_years = get_years()
    return render(request, 'typhoonInfo.html',{'years': unique_years})

def get_typhoon_data(request):
    # 获取前端传过来的台风ID
    typhoon_ids = request.GET.get('typhoon_ids', '').split(',')
    print(typhoon_ids)
    typhoon_data = []

    # 遍历每个台风ID
    for typhoon_id in typhoon_ids:
        # 获取台风的基础信息
        try:
            typhoon_basic_info = TyphoonBasicInfo.objects.get(Typhoon_Id=typhoon_id)
        except TyphoonBasicInfo.DoesNotExist:
            continue

        # 获取路径点数据
        location_info = TyphoonLocationInfo.objects.filter(Typhoon_Id=typhoon_id)

        # 获取路径的最高等级
        grade_info = TyphoonGradeInfo.objects.filter(Typhoon_PathId__in=location_info.values('Typhoon_PathId'))
        max_level = grade_info.aggregate(Max('Typhoon_Level'))['Typhoon_Level__max']


        # 计算台风的持续时间
        if typhoon_basic_info.Typhoon_EndTime and typhoon_basic_info.Typhoon_OnsetTime:
            duration = typhoon_basic_info.Typhoon_EndTime - typhoon_basic_info.Typhoon_OnsetTime
            duration_days = duration.days if duration else 0
        else:
            duration_days = 0

        # 计算平均风速和压强
        avg_wind_speed = grade_info.aggregate(Avg('Typhoon_WindSpeed'))['Typhoon_WindSpeed__avg']
        avg_pressure = grade_info.aggregate(Avg('Typhoon_Pressure'))['Typhoon_Pressure__avg']

        # 计算路径点数
        path_point_count = location_info.count()

        # 构建返回数据
        typhoon_data.append({
            'typhoon_id': typhoon_id,
            'typhoon_name': typhoon_basic_info.Typhoon_CName,
            'avg_wind_speed': avg_wind_speed if avg_wind_speed is not None else 0,
            'avg_pressure': avg_pressure if avg_pressure is not None else 0,
            'max_level': max_level if max_level is not None else 0,
            'path_point_count': path_point_count,
            'duration_days': duration_days,
        })
    return JsonResponse({'data': typhoon_data})

def get_typhoon_data_table(request):
    # 获取前端传过来的台风ID
    typhoon_ids = request.GET.get('typhoon_ids', '').split(',')
    print(typhoon_ids)

    # 创建一个空列表来存储每个台风的数据
    typhoon_data = []

    # 遍历每个台风ID，查询相关数据
    for typhoon_id in typhoon_ids:
        try:
            # 获取台风基本信息
            typhoon = TyphoonBasicInfo.objects.get(Typhoon_Id=typhoon_id)

            # 查询该台风的路径信息
            location_info = TyphoonLocationInfo.objects.filter(Typhoon_Id=typhoon_id)
            grade_info = TyphoonGradeInfo.objects.filter(
                Typhoon_PathId__in=location_info.values_list('Typhoon_PathId', flat=True))

            # 提取所需的信息
            wind_speeds = [grade.Typhoon_WindSpeed for grade in grade_info if grade.Typhoon_WindSpeed is not None]
            levels = [grade.Typhoon_Level for grade in grade_info if grade.Typhoon_Level is not None]
            pressures = [grade.Typhoon_Pressure for grade in grade_info if grade.Typhoon_Pressure is not None]

            max_pressure = max(pressures) if pressures else None
            min_pressure = min(pressures) if pressures else None
            avg_pressure = sum(pressures) / len(pressures) if pressures else None

            # 统计强度分布
            intensity_distribution = {
                intensity: sum(1 for grade in grade_info if grade.Typhoon_Intensity == intensity)
                for intensity, _ in TyphoonGradeInfo.INTENSITY_CHOICES
            }

            # 将结果添加到台风数据列表中
            typhoon_data.append({
                'typhoon_id': typhoon.Typhoon_Id,
                'typhoon_name': typhoon.Typhoon_CName or typhoon.Typhoon_EName,
                'max_pressure': max_pressure,
                'min_pressure': min_pressure,
                'avg_pressure': avg_pressure,
                'wind_speeds': wind_speeds,
                'levels': levels,
                'intensity_distribution': intensity_distribution,
            })

        except TyphoonBasicInfo.DoesNotExist:
            print(f'台风ID {typhoon_id} 不存在')
            continue

    # 返回JSON响应
    return JsonResponse({'data': typhoon_data})

def Information_content(request, infor_id):
    try:
        content = Information.objects.get(pk=infor_id)
    except:
        return render(request,'404.html')
    latest_info = Information.objects.all().order_by('-pub_time')[:10]
    return render(request,'information.html',{'content': content, 'infor_list': latest_info})

@require_POST
def pub_comment(request):
    infor_id = request.POST.get('infor_id')
    comment = request.POST.get('comment')
    author_email = request.session['user_email']
    information = Information.objects.get(id=infor_id)
    author_instance = UserInfo.objects.get(email=author_email)
    InformationComment.objects.create(content=comment, information=information, author=author_instance)
    return redirect(reverse('clientApp:Information_content',kwargs={'infor_id': infor_id}))
